package cn.finyzq.ss.games.web.ctrl;

import cn.finyzq.ss.games.annotation.Public;
import cn.finyzq.ss.games.persist.UserMapper;
import cn.finyzq.ss.games.service.UserService;
import cn.finyzq.ss.games.service.WXConnector;
import cn.finyzq.ss.games.utils.ResultCode;
import cn.finyzq.ss.games.utils.SessionUtils;
import cn.finyzq.ss.games.vo.ResultBean;
import cn.finyzq.ss.games.vo.User;
import cn.finyzq.ss.games.vo.WechatToken;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * Create Time: 2018年08月05日 20:41
 *
 * @author fin
 */
@RestController
@RequestMapping("/api/v1/login")
public class LoginCtrl extends BaseCtrl {

    @Autowired
    private WXConnector wxConnector;

    @Autowired
    private UserService userService;


    @GetMapping("")
    @Public
    public ResultBean login(String code, HttpServletRequest request) {

        WechatToken token;
        if (code != null) {
            token = wxConnector.getWechatTokenByCode(code);
        } else {
            return new ResultBean(ResultCode.AUTH_CODE_CAN_NOT_BE_NULL, "用户登录失败");
        }
        SessionUtils.setSessionAttribute(request, "token", token);

        ResultBean<User> user = userService.findUserByOpenid(token.getOpenid());
        if (user.getStatus() == ResultCode.SUCCESS) {
            SessionUtils.setUser(request, user.getData());
        }


        JSONObject ret = new JSONObject();
        ret.put("authorised", user.getStatus() == ResultCode.SUCCESS);
        ret.put("login", true);
        ret.put("sessionid", request.getSession().getId());
        return success(ret);
    }

    @PostMapping("/authorise")
    @Public
    public ResultBean auth(@RequestBody JSONObject body,  HttpServletRequest request) {

        WechatToken token = SessionUtils.getSession(request, "token", WechatToken.class);
        User user = new User();
        user.setOpenid(token.getOpenid());
        user.setAvatar(body.getString("avatarUrl"));
        user.setNickname(body.getString("nickName"));
        ResultBean ret = this.userService.addUser(user);
        if (ret.getStatus() == ResultCode.SUCCESS) {
            SessionUtils.setUser(request, user);
        }
        return ret;
    }

}
